<template>
  <div class="member-level-container">
    <!-- 搜索和操作区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" ref="searchFormRef" inline>
        <el-form-item label="等级名称">
          <el-input v-model="searchForm.name" placeholder="请输入等级名称" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格区域 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>会员等级列表</span>
          <el-button type="primary" @click="handleAdd">新增等级</el-button>
        </div>
      </template>

      <el-table
        :data="levelList"
        style="width: 100%"
        border
        v-loading="loading"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="name" label="等级名称" width="120" />
        <el-table-column prop="level" label="等级值" width="80" align="center" />
        <el-table-column prop="icon" label="图标" width="80" align="center">
          <template #default="{ row }">
            <el-icon v-if="row.icon" :style="{ color: row.color, fontSize: '24px' }">
              <component :is="row.icon" />
            </el-icon>
          </template>
        </el-table-column>
        <el-table-column prop="color" label="颜色" width="100" align="center">
          <template #default="{ row }">
            <div class="color-block" :style="{ backgroundColor: row.color }"></div>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="等级描述" min-width="180" show-overflow-tooltip />
        <el-table-column prop="pointsRequired" label="所需积分" width="100" align="center" />
        <el-table-column prop="discount" label="折扣比例" width="100" align="center">
          <template #default="{ row }">
            {{ row.discount }}%
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80" align="center">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column label="操作" width="220" fixed="right" align="center">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button type="success" size="small" @click="handleViewBenefits(row)">权益设置</el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 会员等级表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="levelFormRef"
        :model="levelForm"
        :rules="levelRules"
        label-width="100px"
      >
        <el-form-item label="等级名称" prop="name">
          <el-input v-model="levelForm.name" placeholder="请输入等级名称" />
        </el-form-item>
        <el-form-item label="等级值" prop="level">
          <el-input-number v-model="levelForm.level" :min="1" :max="99" controls-position="right" />
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <el-input v-model="levelForm.icon" placeholder="请输入图标名称">
            <template #append>
              <el-button @click="handleSelectIcon">选择</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="颜色" prop="color">
          <el-color-picker v-model="levelForm.color" show-alpha />
        </el-form-item>
        <el-form-item label="等级描述" prop="description">
          <el-input v-model="levelForm.description" type="textarea" :rows="3" placeholder="请输入等级描述" />
        </el-form-item>
        <el-form-item label="所需积分" prop="pointsRequired">
          <el-input-number v-model="levelForm.pointsRequired" :min="0" controls-position="right" />
        </el-form-item>
        <el-form-item label="折扣比例" prop="discount">
          <el-input-number v-model="levelForm.discount" :min="0" :max="100" controls-position="right" />
          <span class="unit">%</span>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="levelForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 图标选择对话框 -->
    <el-dialog v-model="iconDialogVisible" title="选择图标" width="800px">
      <div class="icon-list">
        <div
          v-for="icon in iconList"
          :key="icon"
          class="icon-item"
          @click="handleIconSelect(icon)"
        >
          <el-icon>
            <component :is="icon" />
          </el-icon>
          <div class="icon-name">{{ icon }}</div>
        </div>
      </div>
    </el-dialog>

    <!-- 会员权益设置对话框 -->
    <el-dialog
      v-model="benefitDialogVisible"
      title="会员权益设置"
      width="800px"
    >
      <div class="benefit-header">
        <h3>{{ currentLevel?.name }} - 权益设置</h3>
        <el-button type="primary" @click="handleAddBenefit">新增权益</el-button>
      </div>
      
      <el-table :data="benefitList" border style="width: 100%; margin-top: 20px;">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="name" label="权益名称" width="150" />
        <el-table-column prop="description" label="权益描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="type" label="权益类型" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getBenefitTypeTag(row.type)">{{ getBenefitTypeLabel(row.type) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="value" label="权益值" width="120" />
        <el-table-column label="操作" width="150" fixed="right" align="center">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEditBenefit(row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDeleteBenefit(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 会员权益表单对话框 -->
      <el-dialog
        v-model="benefitFormDialogVisible"
        :title="benefitFormTitle"
        width="500px"
        append-to-body
      >
        <el-form
          ref="benefitFormRef"
          :model="benefitForm"
          :rules="benefitRules"
          label-width="100px"
        >
          <el-form-item label="权益名称" prop="name">
            <el-input v-model="benefitForm.name" placeholder="请输入权益名称" />
          </el-form-item>
          <el-form-item label="权益描述" prop="description">
            <el-input v-model="benefitForm.description" type="textarea" :rows="2" placeholder="请输入权益描述" />
          </el-form-item>
          <el-form-item label="权益类型" prop="type">
            <el-select v-model="benefitForm.type" placeholder="请选择权益类型">
              <el-option v-for="item in benefitTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="权益值" prop="value">
            <el-input v-model="benefitForm.value" placeholder="请输入权益值" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="benefitFormDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="handleSubmitBenefit">确 定</el-button>
          </span>
        </template>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

// 会员等级接口定义
interface MemberLevel {
  id?: number
  name: string
  level: number
  icon: string
  color: string
  description: string
  pointsRequired: number
  discount: number
  status: number
  createTime?: string
}

// 会员权益接口定义
interface MemberBenefit {
  id?: number
  levelId: number
  name: string
  description: string
  type: number
  value: string
}

// 响应式数据
const loading = ref(false)
const levelList = ref<MemberLevel[]>([])
const dialogVisible = ref(false)
const dialogTitle = ref('')
const iconDialogVisible = ref(false)
const benefitDialogVisible = ref(false)
const benefitFormDialogVisible = ref(false)
const benefitFormTitle = ref('')
const isEdit = ref(false)
const isBenefitEdit = ref(false)
const searchFormRef = ref<FormInstance>()
const levelFormRef = ref<FormInstance>()
const benefitFormRef = ref<FormInstance>()
const currentLevel = ref<MemberLevel | null>(null)

// 搜索表单
const searchForm = reactive({
  name: '',
  status: ''
})

// 会员等级表单
const levelForm = reactive<MemberLevel>({
  name: '',
  level: 1,
  icon: '',
  color: '#409EFF',
  description: '',
  pointsRequired: 0,
  discount: 100,
  status: 1
})

// 会员权益表单
const benefitForm = reactive<MemberBenefit>({
  levelId: 0,
  name: '',
  description: '',
  type: 1,
  value: ''
})

// 会员权益列表
const benefitList = ref<MemberBenefit[]>([])

// 图标列表
const iconList = [
  'Star', 'Crown', 'Medal', 'Trophy', 'GoldMedal', 'SilverMedal', 'BronzeMedal',
  'Diamond', 'Sunny', 'Moon', 'MagicStick', 'Cherry', 'Pearl', 'Opportunity'
]

// 权益类型选项
const benefitTypeOptions = [
  { label: '折扣优惠', value: 1 },
  { label: '积分奖励', value: 2 },
  { label: '专属服务', value: 3 },
  { label: '生日特权', value: 4 },
  { label: '免费配送', value: 5 },
  { label: '其他特权', value: 6 }
]

// 表单验证规则
const levelRules: FormRules = {
  name: [
    { required: true, message: '请输入等级名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  level: [
    { required: true, message: '请输入等级值', trigger: 'blur' },
    { type: 'number', min: 1, max: 99, message: '等级值必须在1-99之间', trigger: 'blur' }
  ],
  icon: [{ required: true, message: '请选择图标', trigger: 'change' }],
  color: [{ required: true, message: '请选择颜色', trigger: 'change' }],
  description: [
    { required: true, message: '请输入等级描述', trigger: 'blur' },
    { max: 200, message: '最多输入200个字符', trigger: 'blur' }
  ],
  pointsRequired: [
    { required: true, message: '请输入所需积分', trigger: 'blur' },
    { type: 'number', min: 0, message: '所需积分不能小于0', trigger: 'blur' }
  ],
  discount: [
    { required: true, message: '请输入折扣比例', trigger: 'blur' },
    { type: 'number', min: 0, max: 100, message: '折扣比例必须在0-100之间', trigger: 'blur' }
  ]
}

// 权益表单验证规则
const benefitRules: FormRules = {
  name: [
    { required: true, message: '请输入权益名称', trigger: 'blur' },
    { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入权益描述', trigger: 'blur' },
    { max: 200, message: '最多输入200个字符', trigger: 'blur' }
  ],
  type: [{ required: true, message: '请选择权益类型', trigger: 'change' }],
  value: [
    { required: true, message: '请输入权益值', trigger: 'blur' },
    { max: 100, message: '最多输入100个字符', trigger: 'blur' }
  ]
}

// 初始化数据
onMounted(() => {
  fetchLevelList()
})

// 获取会员等级列表
const fetchLevelList = async () => {
  loading.value = true
  try {
    // 模拟API请求
    setTimeout(() => {
      const mockData: MemberLevel[] = [
        {
          id: 1,
          name: '普通会员',
          level: 1,
          icon: 'Star',
          color: '#909399',
          description: '普通会员，享受基本服务',
          pointsRequired: 0,
          discount: 100,
          status: 1,
          createTime: '2023-01-01 10:00:00'
        },
        {
          id: 2,
          name: '白银会员',
          level: 2,
          icon: 'SilverMedal',
          color: '#C0C4CC',
          description: '白银会员，享受部分优惠',
          pointsRequired: 500,
          discount: 95,
          status: 1,
          createTime: '2023-01-01 10:00:00'
        },
        {
          id: 3,
          name: '黄金会员',
          level: 3,
          icon: 'GoldMedal',
          color: '#E6A23C',
          description: '黄金会员，享受更多优惠',
          pointsRequired: 1500,
          discount: 90,
          status: 1,
          createTime: '2023-01-01 10:00:00'
        },
        {
          id: 4,
          name: '铂金会员',
          level: 4,
          icon: 'Diamond',
          color: '#409EFF',
          description: '铂金会员，享受专属服务',
          pointsRequired: 5000,
          discount: 85,
          status: 1,
          createTime: '2023-01-01 10:00:00'
        },
        {
          id: 5,
          name: '钻石会员',
          level: 5,
          icon: 'Crown',
          color: '#F56C6C',
          description: '钻石会员，享受最高权益',
          pointsRequired: 10000,
          discount: 80,
          status: 1,
          createTime: '2023-01-01 10:00:00'
        }
      ]
      
      levelList.value = mockData
      loading.value = false
    }, 500)
  } catch (error) {
    console.error('获取会员等级列表失败:', error)
    ElMessage.error('获取会员等级列表失败')
    loading.value = false
  }
}

// 搜索会员等级
const handleSearch = () => {
  fetchLevelList()
}

// 重置搜索
const resetSearch = () => {
  if (searchFormRef.value) {
    searchFormRef.value.resetFields()
  }
  handleSearch()
}

// 新增会员等级
const handleAdd = () => {
  resetForm()
  isEdit.value = false
  dialogTitle.value = '新增会员等级'
  dialogVisible.value = true
}

// 编辑会员等级
const handleEdit = (row: MemberLevel) => {
  resetForm()
  isEdit.value = true
  dialogTitle.value = '编辑会员等级'
  Object.assign(levelForm, row)
  dialogVisible.value = true
}

// 删除会员等级
const handleDelete = (row: MemberLevel) => {
  ElMessageBox.confirm('确认删除该会员等级吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      // 模拟删除操作
      setTimeout(() => {
        ElMessage.success('删除成功')
        fetchLevelList()
      }, 500)
    })
    .catch(() => {})
}

// 修改会员等级状态
const handleStatusChange = (row: MemberLevel) => {
  const statusText = row.status === 1 ? '启用' : '禁用'
  ElMessage.success(`会员等级${statusText}成功`)
}

// 提交表单
const handleSubmit = async () => {
  if (!levelFormRef.value) return
  
  await levelFormRef.value.validate((valid) => {
    if (valid) {
      // 模拟提交操作
      setTimeout(() => {
        if (isEdit.value) {
          ElMessage.success('修改成功')
        } else {
          ElMessage.success('新增成功')
        }
        dialogVisible.value = false
        fetchLevelList()
      }, 500)
    }
  })
}

// 重置表单
const resetForm = () => {
  if (levelFormRef.value) {
    levelFormRef.value.resetFields()
  }
  Object.assign(levelForm, {
    name: '',
    level: 1,
    icon: '',
    color: '#409EFF',
    description: '',
    pointsRequired: 0,
    discount: 100,
    status: 1
  })
}

// 关闭对话框
const handleDialogClose = () => {
  resetForm()
}

// 选择图标
const handleSelectIcon = () => {
  iconDialogVisible.value = true
}

// 确认选择图标
const handleIconSelect = (icon: string) => {
  levelForm.icon = icon
  iconDialogVisible.value = false
}

// 查看会员权益
const handleViewBenefits = (row: MemberLevel) => {
  currentLevel.value = row
  benefitForm.levelId = row.id || 0
  fetchBenefitList()
  benefitDialogVisible.value = true
}

// 获取会员权益列表
const fetchBenefitList = async () => {
  try {
    // 模拟API请求
    setTimeout(() => {
      const mockData: MemberBenefit[] = [
        {
          id: 1,
          levelId: currentLevel.value?.id || 0,
          name: '购物折扣',
          description: '享受购物折扣优惠',
          type: 1,
          value: `${currentLevel.value?.discount || 100}%`
        },
        {
          id: 2,
          levelId: currentLevel.value?.id || 0,
          name: '积分奖励',
          description: '购物获得额外积分',
          type: 2,
          value: `${(currentLevel.value?.level || 1) * 10}%`
        },
        {
          id: 3,
          levelId: currentLevel.value?.id || 0,
          name: '专属客服',
          description: '享受专属客服服务',
          type: 3,
          value: '7×24小时'
        }
      ]
      
      benefitList.value = mockData
    }, 300)
  } catch (error) {
    console.error('获取会员权益列表失败:', error)
    ElMessage.error('获取会员权益列表失败')
  }
}

// 新增会员权益
const handleAddBenefit = () => {
  resetBenefitForm()
  isBenefitEdit.value = false
  benefitFormTitle.value = '新增会员权益'
  benefitFormDialogVisible.value = true
}

// 编辑会员权益
const handleEditBenefit = (row: MemberBenefit) => {
  resetBenefitForm()
  isBenefitEdit.value = true
  benefitFormTitle.value = '编辑会员权益'
  Object.assign(benefitForm, row)
  benefitFormDialogVisible.value = true
}

// 删除会员权益
const handleDeleteBenefit = (row: MemberBenefit) => {
  ElMessageBox.confirm('确认删除该会员权益吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      // 模拟删除操作
      setTimeout(() => {
        ElMessage.success('删除成功')
        fetchBenefitList()
      }, 300)
    })
    .catch(() => {})
}

// 提交权益表单
const handleSubmitBenefit = async () => {
  if (!benefitFormRef.value) return
  
  await benefitFormRef.value.validate((valid) => {
    if (valid) {
      // 模拟提交操作
      setTimeout(() => {
        if (isBenefitEdit.value) {
          ElMessage.success('修改成功')
        } else {
          ElMessage.success('新增成功')
        }
        benefitFormDialogVisible.value = false
        fetchBenefitList()
      }, 300)
    }
  })
}

// 重置权益表单
const resetBenefitForm = () => {
  if (benefitFormRef.value) {
    benefitFormRef.value.resetFields()
  }
  Object.assign(benefitForm, {
    levelId: currentLevel.value?.id || 0,
    name: '',
    description: '',
    type: 1,
    value: ''
  })
}

// 获取权益类型标签
const getBenefitTypeLabel = (type: number) => {
  const option = benefitTypeOptions.find(item => item.value === type)
  return option ? option.label : '未知'
}

// 获取权益类型标签样式
const getBenefitTypeTag = (type: number) => {
  switch (type) {
    case 1: return 'success'
    case 2: return 'warning'
    case 3: return 'primary'
    case 4: return 'danger'
    case 5: return 'info'
    case 6: return ''
    default: return ''
  }
}
</script>

<style scoped>
.member-level-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

/* 搜索区域样式优化 */
.search-card .el-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.search-card .el-form-item {
  margin-bottom: 0;
  margin-right: 10px;
}

.search-card .el-form-item:last-child {
  margin-right: 0;
}

/* 增加选择框宽度 */
.search-card .el-select {
  width: 150px;
}

.table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.color-block {
  width: 30px;
  height: 20px;
  border-radius: 4px;
  margin: 0 auto;
}

.unit {
  margin-left: 5px;
  color: #909399;
}

.icon-list {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  max-height: 400px;
  overflow-y: auto;
}

.icon-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 80px;
  height: 80px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.icon-item:hover {
  background-color: #f5f7fa;
  border-color: #409eff;
  color: #409eff;
}

.icon-name {
  margin-top: 5px;
  font-size: 12px;
  text-align: center;
  word-break: break-all;
}

.benefit-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.benefit-header h3 {
  margin: 0;
}

/* 响应式布局 */
@media screen and (max-width: 768px) {
  .member-level-container {
    padding: 10px;
  }
  
  .el-form-item {
    margin-right: 0;
    width: 100%;
  }
  
  .el-dialog {
    width: 90% !important;
  }
  
  .icon-item {
    width: 60px;
    height: 60px;
  }
}
</style>